package com.nowcoder.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class ServiceLogAspect {

    private final static Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    //声明切点，Pointcut织入到哪些对象的哪些位置
    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointCut(){

    }

    //具体在所有方法执行前输出日志
    //用户ip在xxx时间，访问了[com.nowcoder.community.service.xxx()].
    @Before("pointCut()")
    public void before(JoinPoint joinPoint){
        //获取ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //在这一节课中，EventConsumer类中不是调用了MessageService类中的方法吗？
        // 在统一日志处理的时候通过AOP拦截了全部service包中的所有的方法在before时调用了ServletRequestAttributes这个方法，
        // 在EventConsumer调用的MessageService所得到的ServletRequestAttributes肯定是为空的
        if (requestAttributes == null){
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        logger.info(String.format("用户[%s],在[%s],访问了[%s]",ip,date,target));

    }



}
